<?php
/**
 * @author ykm 2015-12-15
 * @describe 京东请求电子面单类
 */
class erpapi_logistics_matrix_360buy_request_electron extends erpapi_logistics_request_electron
{

    public function bufferRequest($sdf){
        return $this->directNum;
    }
    public function etmsRangeCheck($params){
        $this->title = $this->__channelObj->channel['name'] . $this->__channelObj->channel['channel_type'] . '是否京配';
        $this->primaryBn = $params['tid'];
        return $this->requestCall(STORE_ETMS_RANGE_CHECK, $params);
    }
    public function directRequest($sdf){
        $this->primaryBn = $sdf['primary_bn'];
        $this->title = $this->__channelObj->channel['name'] . $this->__channelObj->channel['channel_type'] . '获取电子面单';
        $delivery = $sdf['delivery'];
        $params = array(
            'preNum' => $sdf['preNum']
        );
        $back = $this->requestCall(STORE_ETMS_WAYBILLCODE_GET, $params);
        $back['etms_check'] = $sdf['etms_check'];
        return $this->backToResult($back, $delivery);
    }

    public function backToResult($back, $delivery){
        $data = empty($back['data']) ? '' : json_decode($back['data'], true);
        $etmsCheck = empty($back['etms_check']) ? array() : $back['etms_check'];
        if(empty($data['resultInfo']['deliveryIdList'])) {
            return false;
        }
        $result = array();
        foreach($data['resultInfo']['deliveryIdList'] as $val) {
            $result[] = array(
                'succ' => $val ? true : false,
                'msg' => '',
                'delivery_id' => $delivery['delivery_id'],
                'delivery_bn' => $delivery['delivery_bn'],
                'logi_no' => $val,
                'json_packet' => json_encode($etmsCheck),
                'noWayBillExtend' => false,
            );
            break;
        }
        $this->directDataProcess($result);
        return $result;
    }

    public function delivery($sdf) {

       $delivery = $sdf['delivery'];
        $shop = $sdf['shop'];
        $dlyCorp = $sdf['dly_corp'];
        $totalAmount = $sdf['total_amount'];
        $orderBn = $sdf['order_bn'];
        $receivableAmount = $sdf['receivable_amount'];
        $sameRequest = $sdf['same_request'];
        $this->title = '京东电子面单物流回传';
        $this->primaryBn = $delivery['logi_no'];
        $logData = array(
            'logi_no' => $delivery['logi_no'],
            'delivery_id' => $delivery['delivery_id']
        );
        $params = array();
        $params['deliveryId'] = $delivery['logi_no'];//运单号

        $salePlat=$this->getSalePlat($orderBn);
        $params['salePlat'] = $salePlat;//销售平台编码

        // $params['salePlat'] = '0010001';//销售平台编码
        $params['orderId'] = $delivery['delivery_id'];//ERP发货单
        $params['thrOrderId'] = substr($orderBn,0,98);//京东订单  不能超过100所以先截取
        $params['senderName'] = $shop['default_sender'];//寄件人姓名 必填
        $params['senderAddress'] = $shop['address_detail'];//寄件人地址 必填
        if ($shop['tel']) {
            $params['senderTel'] = $shop['tel'];//寄件人电话
        }
        if ($shop['mobile']) {
            $params['senderMobile'] = $shop['mobile'];//寄件人手机
        }
        if ($shop['zip']) {
            $params['senderPostcode'] = $shop['zip'];//寄件人邮编
        }
        $params['receiveName'] = $delivery['ship_name'];//收件人姓名 必填

        if ($delivery['ship_province']) {
            $params['province'] = $delivery['ship_province'];//收件人省
        }
        if ($delivery['ship_city']) {
            $params['city'] = $delivery['ship_city'];//收件人市
        }
        if ($delivery['ship_district']) {
            $params['county '] = $delivery['ship_district'];//收件人县
        }

        if ((strpos($delivery['ship_addr'],$delivery['ship_province']) !== false) && (strpos($delivery['ship_addr'],$delivery['ship_city']) !== false) && (strpos($delivery['ship_addr'],$delivery['ship_district']) !== false)){

             $params['receiveAddress'] = $delivery['ship_addr'];
        }else{
            $params['receiveAddress'] = "(".$delivery['ship_province'].$delivery['ship_city'].$delivery['ship_district'].")".$delivery['ship_addr'];//收件人地址 必填
        }
        
        if ($delivery['ship_tel']) {

            if(preg_match("/^1[3456789]\d{9}$/", $delivery['ship_tel']))
            {
                $params['receiveMobile'] = $delivery['ship_tel'];//收件人手机
            }else{
                $params['receiveTel'] = $delivery['ship_tel'];//收件人电话
            }
        }
        if ($delivery['ship_mobile'])
         {
            if(preg_match("/^1[3456789]\d{9}$/", $delivery['ship_mobile']))
            {
                $params['receiveMobile'] = $delivery['ship_mobile'];//收件人手机
            }

            if(preg_match("/^([0-9]{3,4}-)?[0-9]{7,8}$/", $delivery['ship_mobile']))
            {
                $params['receiveTel'] = $delivery['ship_mobile'];//收件人电话
            }

        }
        if ($delivery['ship_zip']) {
            $params['postcode'] = $delivery['ship_zip'];//收件人邮编
        }
        $params['packageCount'] = 1;//包裹数量
        $params['weight'] = ($delivery['weight']) > 0 ? sprintf("%.2f", (max(0, $delivery['weight']) / 1000)) : 0;//重量
        $params['vloumn'] = 0;//体积
        //是否代收货款
        if ($delivery['is_cod'] == 'true') {
            $params['collectionValue'] = 1;//是否代收货款
            $params['collectionMoney'] = $receivableAmount;//代收货款金额
        } else {
            $params['collectionValue'] = 0;//是否代收货款
        }
        if($dlyCorp['protect'] == 'true') {
            $params['guaranteeValue'] = 1;//是否保价
            $params['guaranteeValueAmount'] = sprintf('%.2f', max($totalAmount * $dlyCorp['protect_rate'], $dlyCorp['minprice']));
        } else {
            $params['guaranteeValue'] = 0;//是否保价
        }
        $this->deliveryCall(STORE_ETMS_WAYBILL_SEND,$logData,$params);
        if(!empty($sameRequest)) {
            foreach($sameRequest as $value) {
                $params['thrOrderId'] = substr($value['order_bn'],0,98);//京东订单  不能超过100所以先截取
                if ($delivery['is_cod'] == 'true') {
                    $params['collectionMoney'] = $value['receivable_amount'];//代收货款金额
                }
                if($dlyCorp['protect'] == 'true') {
                    $totalAmount = $value['total_amount'];
                    $params['guaranteeValueAmount'] = sprintf('%.2f', max($totalAmount * $dlyCorp['protect_rate'], $dlyCorp['minprice']));
                }
                $this->deliveryCall(STORE_ETMS_WAYBILL_SEND,$logData,$params);
            }
        }

        error_log(print_r($logData,1).PHP_EOL,3,DATA_DIR.'/sync_jd_'.date('Y-m-d').'.log');
        error_log(print_r($params,1).PHP_EOL,3,DATA_DIR.'/sync_jd_'.date('Y-m-d').'.log');
        return true;
    }


   public  function getSalePlat($order_bn)
   {
        $orderData=app::get('ome')->model('orders')->getRow(array('order_bn'=>$order_bn),'shop_id');
        $shopData=app::get('ome')->model('shop')->getRow(array('shop_id'=>$orderData['shop_id']),'shop_type');
        switch ($shopData['shop_type']) {
            case 'taobao':
            case 'alibaba':
                $salePlat='0010002';
                break;
            case '360buy':
                $salePlat='0010001';
                break;
            case 'amazon':
                $salePlat='0010004';
                break;
            case 'suning':
                $salePlat='0010003';
                break;
            default:
                $salePlat='0030001';
                break;
        }
        return $salePlat;
   }

}
